﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;

namespace Performance_Test
{
    public partial class Form2 : Form
    {
        List<string> config_data = new List<string>();
        SerialPort ComPort;
    
        public Form2(SerialPort port)
        {
            InitializeComponent();
            ComPort = port;
          
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            config_data.Clear();
            openFileDialog1.Filter = "txt files (*.txt)|*.txt";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                System.IO.StreamReader sr = new
                   System.IO.StreamReader(openFileDialog1.FileName);

                while (sr.Peek() >= 0)
                {

                    config_data.Add(sr.ReadLine());
                    config_data.ToArray();
                }
                for (int i = 0; i < config_data.Count; i++)
                {
                    listBox1.Items.Add(config_data[i]);

                }

                sr.Close();

            }
        }
    
        public static string Command(string data)
        {
            string _command = "", first_char; ;
            int len=0, position;
            len = data.Length;
            if (len != 0)
            {
                first_char = data.Substring(0,1);
                if (first_char == "$")
                {
                    
                    position = string_position(";", data);
                    if (position >= 0)
                    {

                        _command = data.Substring(0, position);
                    }
                    return _command.Trim();
                }
                else
                {
                    return "";
                }
            }
            else
            {
                return "";
            }

        }
        public static int string_position(string substring, string data)
        {
            int position = 0;
            position = data.IndexOf(substring,0);
            return position;
        }

        private void btnWrite_Click_1(object sender, EventArgs e)
        {
            string respond;
            string line;
            
            int baud = ComPort.BaudRate;
            if (ComPort.IsOpen)
            {
                //enter service port mode
                respond = ComPort.ReadExisting();
            //    ComPort.DiscardInBuffer();//delete all data in device's received buffer
            //    ComPort.DiscardOutBuffer();// delete all data in transmit buffer
             //   System.Threading.Thread.Sleep(500);
                respond = ComPort.ReadExisting();
                try
                {
                    line = "$S\r";
                    ComPort.Write(line);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString().Trim(), "error");
                }
                respond = ComPort.ReadExisting();
                System.Threading.Thread.Sleep(500);
                respond = ComPort.ReadExisting();
                if (respond.Contains("$>"))
                {
                    //***********change baudrate to 115200**********
                    ComPort.BaudRate = 115200;
                    for (int i = 0; i < config_data.Count; i++)
                    {
                        line = Command(config_data[i]);
                        if (line != "")
                        {
                            line += "\r";
                            try
                            {
                                ComPort.Write(line);
                                System.Threading.Thread.Sleep(200);
                                respond = ComPort.ReadExisting();
                                richTextBox1.Invoke(new EventHandler(delegate
                                {

                                    richTextBox1.Text += line;
                                    richTextBox1.Text += respond;

                                }));
                                this.progressBar1.Increment(1);
                            }
                            catch (Exception ex)
                            {
                                GC.ReRegisterForFinalize(ComPort.BaseStream);
                                ComPort.Close();
                                GC.ReRegisterForFinalize(ComPort);
                                MessageBox.Show(ex.ToString().Trim(), "Error");
                           
                            }

                        }
                        
                    }
                    //exist service port mode
                    ComPort.Write("$s\r");
                    System.Threading.Thread.Sleep(500);
                 //   ComPort.DiscardInBuffer();//delete all data in device's received buffer
                  //  ComPort.DiscardOutBuffer();// delete all data in transmit buffer
                    //**set baudrate back origin**********
                    ComPort.BaudRate = baud;
                    
                   
                }
                else
                {
                    MessageBox.Show("enter service port mode: failed");
                }
            }
            else
            {
                MessageBox.Show("Please open COM PORT ");

            }
        }

        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {

                GC.ReRegisterForFinalize(ComPort.BaseStream);
                ComPort.Close();
                GC.ReRegisterForFinalize(ComPort);
            }
            catch (Exception ex)
            {
                MessageBox.Show("The device is changed to another interface", "Error");
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            
            this.Close();
        }
    }
}
